function mat= HS_moment_condition_generalized_spec2(data,theta,derivative_flag)
%Calculate the nonlinear Euler equation moment conditions from
%Hansen and Singleton (1982).  When derivative_flag==0 the function
%calculaes the moment conditions, while when derivative_flag==1 it
%caculates the jacobian of the moments

w=data(:,1);
r=data(:,2);
rf=data(:,3);
Z=data(:,4:end);
beta=theta(1);
gamma=theta(2);
if derivative_flag==0
    eta=[(beta*r.*(w.^(-gamma)))-1 (beta*rf.*(w.^(-gamma)))-1];
    mat=kron(eta,ones(1,size(Z,2)/2)).*Z;
else
    qmat1=[repmat(r.*(w.^(-gamma)),1,size(Z,2)/2) ...
        repmat(rf.*(w.^(-gamma)),1,size(Z,2)/2)].*Z;
    qmat2=[repmat(-beta*r.*log(w).*(w.^(-gamma)),1,size(Z,2)/2) ...
         repmat(-beta*rf.*log(w).*(w.^(-gamma)),1,size(Z,2)/2)].*Z;
    mat=zeros(size(qmat1,1),size(qmat1,2),2);
    mat(:,:,1)=qmat1;
    mat(:,:,2)=qmat2;
end
end